/**
 * 
 */
package ar.com.gtug.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

import ar.com.gtug.model.Location;

/**
 * @author Juan M. Irungaray (juan@irungaray.com.ar)
 *
 */
public class LocationService {

	public static Location getLocation(String city, String state, String country){
		Location result = new Location();
		try {
			String rawURL = "http://maps.google.com/maps/api/geocode/json?sensor=false&address="
					+ city + ",+" + state + ",+" + country;
			URL url = new URL(rawURL.replace(" ", "%20"));
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					url.openStream()));
			StringBuilder response = new StringBuilder();
			String line;

			while ((line = reader.readLine()) != null) {
				response.append(line);
			}
			reader.close();
			JSONObject json = new JSONObject(response.toString());
			String status = json.getString("status");
			JSONArray array = json.getJSONArray("results");
			JSONObject location = ((JSONObject) array.get(0)).getJSONObject(
					"geometry").getJSONObject("location");
			
			String address = ((JSONObject) array.get(0))
					.getString("formatted_address");
			String[] addressElements = address.split(", ");
			result.setCity(addressElements[0]);
			result.setState(addressElements[1]);
			result.setCountry(addressElements[2]);
			result.setLatitude(location.getDouble("lat"));
			result.setLongitude(location.getDouble("lng"));

		} catch (Exception e) {
			e.printStackTrace();
			
		}
		return result;
	}
}
